package com.blackteachan.server.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.blackteachan.server.model.User;
import com.blackteachan.server.response.ServerResponseUtil;
import com.blackteachan.server.utils.SpringUtil;
import com.blackteachan.server.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSONObject;
import com.blackteachan.server.service.SysLogService;
import com.blackteachan.server.service.TokenManager;

/**
 * 退出登录<br>
 * web退出和restful方式退出<br>
 * 后者会删除缓存的token
 * 
 * @author blackteachan
 * 创建时间：2017年8月13日
 */
@Slf4j(topic = "adminLogger")
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter {

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		String loginToken = RestfulFilter.getToken(request);
		User user = UserUtil.getCurrentUser();
		if (StringUtils.isBlank(loginToken)) {
			if(user != null) {
                // 非Restful方式
                boolean flag = super.preHandle(request, response);
                log.debug("{}退出成功", user.getUsername());
                SpringUtil.getBean(SysLogService.class).save(user.getId(), "退出", true, null);

                return flag;
            }else {
			    log.debug("用户未登录");
			    return false;
            }
		} else {
			TokenManager tokenManager = SpringUtil.getBean(TokenManager.class);
			boolean flag = tokenManager.deleteToken(loginToken);
			if (flag) {
				RestfulFilter.writeResponse(WebUtils.toHttp(response), HttpStatus.OK.value(), SUCCESS_INFO);
				log.debug("{}退出成功", user.getUsername());
			} else {
				RestfulFilter.writeResponse(WebUtils.toHttp(response), HttpStatus.BAD_REQUEST.value(), ERR_INFO);
			}

			SpringUtil.getBean(SysLogService.class).save(user.getId(), "token方式退出", flag, null);

			return false;
		}
	}

	private static String SUCCESS_INFO = JSONObject.toJSONString(ServerResponseUtil.success("退出成功"));
	private static String ERR_INFO = JSONObject.toJSONString(ServerResponseUtil.fail("退出失败，token不存在"));

}
